package com.shao.discovery;

import com.shao.constant.ZookeeperCons;
import com.shao.discovery.impl.NacosRegistry;
import com.shao.discovery.impl.ZookeeperRegistry;
import com.shao.exception.DiscoveryException;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.common.StringUtils;

/**
 * @author PaoFu
 * @version 1.0
 * @data 2025/4/3 15:27
 */
@Slf4j
public class RegistryConfig {

    @SuppressWarnings("all")
    private final String connectString;

    public RegistryConfig(String connectString) {
        this.connectString = connectString;
    }

    /**
     * 根据需要的内容返回具体的注册中心类型或者地址
     * @param connectString 链接字符串
     * @param isType 是链接类型
     * @return String
     */
    private String getConnectStringTypeOrAddr(String connectString, boolean isType) {
        // zookeeper://127.0.0.1:2181
        String connectStringType = connectString.substring(0, connectString.indexOf("://")).trim();
        String connectStringAddr = connectString.substring(connectString.lastIndexOf("://") + 3).trim();
        if (StringUtils.isBlank(connectStringType) || StringUtils.isBlank(connectStringAddr)) {
            throw new RuntimeException("配置的链接地址错误");
        }
        return isType ? connectStringType : connectStringAddr;
    }

    /**
     * 使用工厂方法设计注册中心的类型
     * @return 返回具体实现的注册中心
     */
    public Registry getRegistry() {
        String connectStringType = getConnectStringTypeOrAddr(connectString, true).toLowerCase();
        String connectStringAddr = getConnectStringTypeOrAddr(connectString, false).toLowerCase();
        if (connectStringType.equals("zookeeper")) {
            log.info("connectStringAddr - {}", connectStringAddr);
            return new ZookeeperRegistry(connectStringAddr, ZookeeperCons.DEFAULT_SESSION_TIMEOUT);
        } else if (connectStringType.equals("nacos")) {
            return new NacosRegistry();
        }
        throw new DiscoveryException("找不到与配置匹配的链接地址");
    }
}
